import axios from "axios";
import {ElMessage, ElMessageBox} from 'element-plus';

const instance = axios.create({
    baseURL: "/api",
    timeout: 5000,
    timeoutErrorMessage: '网络异常',
});

instance.interceptors.request.use(config => {
    config.headers = {
        ...config.headers,
        'X-Menu-Id': config.data ? config.data.menuId : config.params?.menuId,
        'X-Authorization': window.localStorage.getItem("token"),
    }
    return config;
}, err => {
    return Promise.reject(err);
});

instance.interceptors.response.use(response => {
    return response;
}, error => {
    if (error.response.status === 401) {
        localStorage.clear();
        ElMessageBox.alert('登录过期，请重新登录', '提示', {
            confirmButtonText: '去登录',
            showClose: false,
            type: 'error',
            callback: () => {
                window.location.href = '/login';
            }
        });
    } else if (error.response.status === 400) {
        error.response.data.message ? ElMessage.error(error.response.data.message) :
            error.response.data.text().then(m => ElMessage.error(JSON.parse(m).message));
    } else if (error.response.status === 403) {
        ElMessage.error('你没有此项的操作权限或权限不足');
    } else {
        ElMessage.error('网络异常：'.concat(error.response.status));
    }
    return Promise.reject(error);
});

export default instance;
